<template>
  <div class="user-info-container">
    <!-- 搜索和操作区域 -->
    <div class="operation-area">
      <el-input
        v-model="searchQuery"
        placeholder="请输入ID或昵称"
        style="width: 300px; margin-right: 10px"
        @keyup.enter.native="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
      
      <el-button type="primary" @click="handleAdd">新增用户</el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedUsers.length">批量删除</el-button>
      <el-button type="success" @click="exportToExcel">导出Excel</el-button>
      <el-button type="warning" @click="importFromExcel">导入Excel</el-button>
    </div>

    <!-- 用户信息表格 -->
    <el-table
      :data="filteredUsers"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column label="头像" width="100">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" class="user-avatar" />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="age" label="年龄" width="80"></el-table-column>
      <el-table-column prop="gender" label="性别" width="80"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="role" label="身份"></el-table-column>
      <el-table-column prop="disease" label="病情信息"></el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalUsers"
    ></el-pagination>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="userForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="userForm.age" :min="0" :max="120"></el-input-number>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="userForm.gender">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="身份">
          <el-select v-model="userForm.role" placeholder="请选择身份">
            <el-option label="管理员" value="管理员"></el-option>
            <el-option label="普通用户" value="普通用户"></el-option>
          </el-select>
        </el-form-item>
        <!-- 动态显示病情信息输入框 -->
        <el-form-item label="病情信息" v-if="userForm.role === '普通用户'">
          <el-input type="textarea" v-model="userForm.disease"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUserForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { exportJsonToExcel } from '@/utils/export2Excel'
import * as XLSX from 'xlsx'

export default {
  name: 'UserInfoManagement',
  data() {
    return {
      users: [
        // 模拟数据
        {
          id: 1,
          username: '张三',
          avatar: require('@/assets/images/Avatar1.png'),
          age: 28,
          gender: '男',
          phone: '13800138000',
          email: 'zhangsan@example.com',
          role: '管理员',
          disease: '无'
        },
        // 可以添加更多模拟数据
      ],
      searchQuery: '',
      selectedUsers: [],
      currentPage: 1,
      pageSize: 10,
      dialogVisible: false,
      dialogTitle: '新增用户',
      userForm: {
        id: '',
        username: '',
        avatar: '',
        age: 0,
        gender: '男',
        phone: '',
        email: '',
        role: '',
        disease: ''
      },
      avatarOptions: [],
      isEdit: false
    }
  },
  computed: {
    filteredUsers() {
      return this.users.filter(user => {
        return (
          user.id.toString().includes(this.searchQuery) ||
          user.username.includes(this.searchQuery)
        )
      })
    },
    totalUsers() {
      return this.filteredUsers.length
    }
  },
  methods: {
    handleSearch() {
      // 搜索逻辑已在computed中实现
    },
    handleSelectionChange(val) {
      this.selectedUsers = val
    },
    handleAdd() {
      this.dialogTitle = '新增用户'
      this.userForm = {
        id: '',
        username: '',
        avatar: '',
        age: 0,
        gender: '男',
        phone: '',
        email: '',
        role: '',
        disease: ''
      }
      this.isEdit = false
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑用户'
      this.userForm = JSON.parse(JSON.stringify(row))
      this.isEdit = true
      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm('确定要删除该用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.users.findIndex(user => user.id === row.id)
        this.users.splice(index, 1)
        this.$message.success('删除成功')
      })
    },
    handleBatchDelete() {
      this.$confirm('确定要删除选中的用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.selectedUsers.map(user => user.id)
        this.users = this.users.filter(user => !ids.includes(user.id))
        this.selectedUsers = []
        this.$message.success('删除成功')
      })
    },
    submitUserForm() {
      if (this.userForm.role === '管理员') {
        this.userForm.disease = '无';
      }
      if (this.isEdit) {
        const index = this.users.findIndex(user => user.id === this.userForm.id)
        this.users.splice(index, 1, this.userForm)
        this.$message.success('修改成功')
      } else {
        const newId = this.users.length > 0 ? Math.max(...this.users.map(user => user.id)) + 1 : 1
        this.userForm.id = newId
        this.users.push(this.userForm)
        this.$message.success('添加成功')
      }
      this.dialogVisible = false
    },
    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    exportToExcel() {
      const tHeader = ['ID', '用户名', '年龄', '性别', '手机号', '邮箱', '身份', '病情信息']
      const filterVal = ['id', 'username', 'age', 'gender', 'phone', 'email', 'role', 'disease']
      const data = this.users.map(user => {
        return filterVal.map(key => user[key])
      })
      exportJsonToExcel(tHeader, data, '用户信息')
    },
    handleAvatarSuccess(res, file) {
      this.userForm.avatar = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    importFromExcel() {
      this.$confirm('导入Excel将在现有数据基础上增加新数据，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.xlsx, .xls';
        
        input.onchange = e => {
          const files = e.target.files;
          if (files.length <= 0) return;
          
          const fileReader = new FileReader();
          fileReader.onload = event => {
            try {
              const data = new Uint8Array(event.target.result);
              const workbook = XLSX.read(data, { type: 'array' });
              const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
              const jsonData = XLSX.utils.sheet_to_json(firstSheet);
              
              // 获取当前最大ID
              const maxId = this.users.length > 0 ? Math.max(...this.users.map(user => user.id)) : 0;
              
              // 转换数据格式并追加到现有数据
              const importedUsers = jsonData.map((item, index) => ({
                id: maxId + index + 1, // 确保ID不重复
                username: item.用户名 || '',
                avatar: require('@/assets/images/Avatar1.png'),
                age: item.年龄 || 0,
                gender: item.性别 || '男',
                phone: item.手机号 || '',
                email: item.邮箱 || '',
                role: item.身份 || '普通用户',
                disease: item.病情信息 || '无'
              }));
              
              this.users = [...this.users, ...importedUsers];
              this.$message.success(`成功导入${importedUsers.length}条用户数据`);
            } catch (error) {
              this.$message.error('导入失败，请检查文件格式');
              console.error(error);
            }
          };
          
          fileReader.readAsArrayBuffer(files[0]);
        };
        
        input.click();
      }).catch(() => {
        this.$message.info('已取消导入');
      });
    }
  }
}
</script>

<style scoped>
.user-info-container {
  padding: 20px;
}

.operation-area {
  margin-bottom: 20px;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.avatar-option {
  width: 30px;
  height: 30px;
  vertical-align: middle;
  margin-right: 10px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>